#include<iostream>
#include<pthread.h>
#include<unistd.h>
#include<vector>
using namespace std;

pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond=PTHREAD_COND_INITIALIZER;

struct threadData
{
    string _threadName;
    threadData(int num)
        : _threadName("thread" + to_string(num))
    {
    }
    threadData() = default;
};

void *routine(void *args)
{
    threadData *data = static_cast<threadData *>(args);
    {

        for (int i = 0; i < 5; i++)
        {
            pthread_mutex_lock(&mutex);
            pthread_cond_wait(&cond,&mutex);
            printf("I am %s\n", data->_threadName.c_str());
            pthread_mutex_unlock(&mutex);
            pthread_cond_signal(&cond);
        }
    }
}

int main()
{
    vector<pthread_t> tids;
    for(int i=0;i<3;i++)
    {
        pthread_t tid;
        threadData *data = new threadData(i);
        pthread_create(&tid, nullptr, routine, data);
        tids.push_back(tid);
    }
    sleep(1);
    pthread_cond_signal(&cond);
    void *retData;
    for(auto it:tids)
    {
        void *retData;
        pthread_join(it,&retData);
    }

    return 0;
}
